import cherrypy
from django.utils import simplejson

from google.appengine.ext.db import Error

from app.controllers.department import DepartmentController
from app.dutil import toClass

class DepartmentHandler(object):
	@cherrypy.expose
	def index(self):
		pass
		
	@cherrypy.expose	
	def departments(self, *args, **kwargs):
		rsDepartments = DepartmentController.getDepartments()
		dDepartment = dict([('page',1), ('rows',[rDepartment.toCells() for rDepartment in rsDepartments])])
		dDepartment.update(total=len(dDepartment['rows']))
		return simplejson.dumps(dDepartment)
		
	@cherrypy.expose
	def vdept(self,id=None):
		try:
			rsDept = DepartmentController.getDepartment(int(id))
			dDept = rsDept.toRow()
			return simplejson.dumps(dDept)
		except TypeError:
			return None
			
	@cherrypy.expose
	def udept(self, *args, **kwargs):
		if kwargs:
			brs = DepartmentController.updateDepartment(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def adept(self, *args, **kwargs):
		if kwargs:
			brs = DepartmentController.addDepartment(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def ddept(self, id=None):
		if id is not None:
			brs = DepartmentController.deleteDepartment(id)
		else: brs = False
		
		return simplejson.dumps(dict([('success',brs)]))